<?php

namespace app\home\controller;

use app\common\controller\BaseController;
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibMemberDistribute;
use app\common\model\LibUser;
use app\common\model\blfyy\LibStatistic;
use app\common\model\blfyy\LibForm;
use app\common\model\LibUserCode;
use think\Db;
use wechatUtil\WeChatOAuth;
use wxAppUtil\AccessToken;
use wxAppUtil\Curl;
use common\Common;
use wxAppUtil\WXUserUtil;
use app\common\model\UtilConfig;

/**
 * 微信小程序控制器
 * @name wxStore.php
 * @package pnkj
 * @category controller
 * @link http://www.changekeji.com
 * @author moon & ljj
 * @version 2.0
 * @copyright CHANGE INC
 * @since 2017-01-20
 */
class WxStore extends BaseController
{
    private $lib_user;
    private $lib_statistic;
    private $lib_form;
    private $LibUserCode;

    /**
     * 构造函数
     */
    function __construct()
    {
        parent::__construct();
        error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_WARNING);
        $this->lib_user = new LibUser();
        $this->lib_statistic = new LibStatistic();
        $this->lib_form = new LibForm();
        $this->LibUserCode = new LibUserCode();
    }


    /*****************************************添加统计*********************************************/
    function insertData()
    {
        $type = input('type');
        $data = array(
            'type' => $type
        );
        $result = $this->lib_statistic->addStatistic($data);
    }

    /**
     * Info: 表单提交
     * Date: 2022/11/28 10:01
     */
    function addForm()
    {
        $data = array(
            'user_id' => input('user_id'),
            'openID' => input('open_id'),
            'nick_name' => input('nick_name'),
            'head_img_url' => input('head_img_url'),
            'name' => input('name'),
            'interests' => input('interests'),
            'phone' => input('phone'),
            'weChat' => input('wechat'),
            'platform' => input('platform'),
        );
        $result = $this->lib_form->addForm($data);
        echo json_encode($result);
    }


    //*****************************************获取用户信息模块*********************************************

    /**
     * Info: 获取用户opend_id
     * Date: 2022/11/28 10:01
     */
    function getOpendIdByCode()
    {
        //获取用户openId
        $result = WeChatOAuth::getAccessTokenAndOpenId(input('code'));
        $fansInfo = WeChatOAuth::getUserInfo($result['access_token'], $result["openid"]);
        if (isset($result['openid'])) {//获取到opend_id  判断是否存在用户信息
            $libUser = new LibUser();
            $userInfo = $libUser->findUser(['open_id' => $result['openid']]);
            if ($userInfo['errorCode'] == 0) {//存在则直接返回用户信息
                echo json_encode(Common::errorArray(0, '有用户信息，openid获取成功', ['userInfo' => $userInfo['data'],'openid' => $fansInfo]));
            } else {//返回opend_id  返回码为2
                echo json_encode(Common::errorArray(2, '无用户信息，openid获取成功', ['openid' => $fansInfo]));
            }
        } else {
            echo json_encode(Common::errorArray(1, '获取失败，请重新获取', false));
        }
    }

    /**
     * Info: 插入用户信息
     * Date: 2022/11/28 10:01
     */
    function addUser()
    {
        $getInfo = $this->getArgsList(['opendId', 'nickName', 'city', 'avatarUrl', 'country', 'province', 'gender', 'parent_id']);
        $lib_user = new LibUser();
        //判断用户是否存在base_user表中
        $userResult = $lib_user->findUser(array('account' => $getInfo['opendId']));
        if ($userResult['errorCode'] == 1) {
            if ($getInfo['parent_id'] && ($getInfo['parent_id'] == $userResult['data']['id'])) {
                $getInfo['parent_id'] = 0;
            }
            $addInfo = array(
                'nick_name' => $getInfo['nickName'],
                'open_id' => $getInfo['opendId'],
                'account' => $getInfo['opendId'],
                'sex' => $getInfo['gender'],
                'country' => $getInfo['country'],
                'province' => $getInfo['province'],
                'city' => $getInfo['city'],
                'head_img_url' => $getInfo['avatarUrl'],
                'parent_id' => $getInfo['parent_id'],
            );
            $lib_user->addUser($addInfo);
            $userResult = $lib_user->findUser(array('account' => $addInfo['open_id']));
            echo json_encode(Common::errorArray(0, '保存成功', $userResult['data']));
        } else {
            //如果存在用户
            echo json_encode($userResult);
        }
    }

    /**
     * Info: 更新用户信息
     * Date: 2022/11/28 10:01
     */
    function editUser()
    {
        $getInfo = $this->getArgsList(['opendId', 'nickName', 'city', 'avatarUrl', 'country', 'province', 'gender', 'parent_id']);
        $lib_user = new LibUser();
        //判断用户是否存在base_user表中
        $userResult = $lib_user->findUser(array('account' => $getInfo['opendId']));
        if ($userResult['errorCode'] == 0) {
            $addInfo = array(
                'nick_name' => $getInfo['nickName'],
                'country' => $getInfo['country'],
                'province' => $getInfo['province'],
                'city' => $getInfo['city'],
                'head_img_url' => $getInfo['avatarUrl'],
            );
            $lib_user->updateUser(['account' => $getInfo['opendId']],$addInfo);
            $userResult = $lib_user->findUser(array('account' => $getInfo['opendId']));
            echo json_encode(Common::errorArray(0, '保存成功', $userResult['data']));
        }
    }

    /**
     * Info: 更新用户头像
     * Date: 2022/11/28 9:58
     */
    function updateUserAvatar ()
    {
        $getInfo = $this->getArgsList(['id', 'head_img_url']);
        file_put_contents('wxstore.log',json_encode($getInfo,JSON_UNESCAPED_UNICODE));
        $lib_user = new LibUser();
        $userResult = $lib_user->findUser(array('id' => $getInfo['id']));
        if ($userResult['errorCode'] == 0) {
            $addInfo = array(
                'head_img_url' => $getInfo['head_img_url'],
            );
            $lib_user->updateUser(['id' => $getInfo['id']],$addInfo);
            $userResult = $lib_user->findUser(array('id' => $getInfo['id']));
            echo json_encode(Common::errorArray(0, '保存成功', $userResult['data']));die();
        }
        echo json_encode(Common::errorArray(1, '更新失败', false));die();
    }

    /**
     * Info: 更新用户位置
     * Date: 2022/11/28 9:58
     */
    function updateUserLocation ()
    {
        $getInfo = $this->getArgsList(['id', 'lat', 'lng']);
        $lib_user = new LibMember();
        $userResult = $lib_user->findMember(array('user_id' => $getInfo['id']));
        if ($userResult['errorCode'] == 0) {
            $addInfo = array(
                'lat' => $getInfo['lat'],
                'lng' => $getInfo['lng'],
            );
            $lib_user->updateMember(['user_id' => $getInfo['id']],$addInfo);
            $userResult = $lib_user->findMember(array('user_id' => $getInfo['id']));
            echo json_encode(Common::errorArray(0, '保存成功', $userResult['data']));die();
        }
        echo json_encode(Common::errorArray(1, '更新失败', false));die();
    }

    /**
     * Info: 绑定用户关系
     * Date: 2022/11/28 9:58
     */
    function bindUserRelate ()
    {
        //$getInfo = $this->getArgsList($this,['open_id', 'parent_id']);
        $open_id = input('open_id','');
        $parent_id = input('parent_id','');
        (new \app\common\model\service\LibMemberDistribute($open_id,$parent_id))->bindUser();
        echo json_encode(Common::errorArray(0, 'success', true));
    }


    /**
     * Info: 微信小程序用户登录
     * Date: 2022/11/28 9:58
     */
    function wxLogin()
    {
        $lib_config = new UtilConfig('weixin_config');
        $config = $lib_config->findConfigKeyValue('wechat');
        $appid = $config['data']['wxapp_appid'];
        $secret = $config['data']['wxapp_appsecret'];
        $js_code = input('param.js_code');
        if ($js_code != null && $js_code != "") {
            $result = WXUserUtil::get3rd_session($appid, $secret, $js_code);
            //以3rd_session为key,session_key+openid为value，写入session
            $session_key = $result['session_key'];
            $openid = $result['openid'];
            $third_session_key = $result['third_session'];
            $thrid_session_value = $session_key . $openid;
            session("third_session_key", $thrid_session_value);
            echo json_encode($thrid_session_value);
        } else {
            session("third_session_key", '');
        }
    }


    /**
     * Info: 解密用户敏感信息 包括用户openId、nick_name等信息
     * Date: 2022/11/28 10:00
     */
    function decryptUserInfo()
    {
        $lib_config = new UtilConfig('weixin_config');
        $config = $lib_config->findConfigKeyValue('wechat');
        $encryptedData = input('param.encryptedData');
        $iv = input('param.iv');
        $thridRD = input('param.thridRDSession');
        $did = input('param.user_id');
        $appid = $config['data']['wxapp_appid'];
        $encryptedData = trim($encryptedData, chr(239) . chr(187) . chr(191));
        $iv = trim($iv, chr(239) . chr(187) . chr(191));
        $rdSession_key = trim($thridRD, chr(239) . chr(187) . chr(191));
        $sessionArr = explode("==", $rdSession_key);
        $sessionKeys = $sessionArr[0];
        $sessionKey = $sessionKeys . '==';
        $account = $sessionArr[1];
        //判断用户是否存在
        $lib_user = new LibUser();
        //判断用户是否存在base_user表中
        $userResult = $lib_user->findUser(array('account' => $account));
        if ($userResult['errorCode'] == 0) {
            echo json_encode($userResult['data']);
        } else {
            $result = WXUserUtil::decryptUserInfo($appid, $sessionKey, $encryptedData, $iv);
            $userInfo = $this->insertUser($result, $did);
            echo json_encode($userInfo);
        }
    }

    /**
     * Info: 插入用户信息
     * Date: 2022/11/28 10:00
     */
    function insertUser($userInfo, $did)
    {
        $addInfo = array(
            'nick_name' => $userInfo['nickName'],
            'open_id' => $userInfo['openId'],
            'account' => $userInfo['openId'],
            'sex' => $userInfo['gender'],
            'country' => $userInfo['country'],
            'province' => $userInfo['province'],
            'city' => $userInfo['city'],
            'head_img_url' => $userInfo['avatarUrl'],
            'parent_id' => $did
        );
        $lib_user = new LibUser();
        //判断用户是否存在base_user表中
        $userResult = $lib_user->findUser(array('account' => $userInfo['openId']));
        if ($userResult['errorCode'] != 0) {
            $result = $lib_user->addUser($addInfo);
            $addInfo['id'] = $result['data'];
            return $addInfo;
        } else {
            //如果存在用户
            return $userResult['data'];
        }
    }

    /**
     * Info: 获取用户信息
     * Date: 2022/11/28 10:00
     */
    function getUserInfo()
    {
        $id = input("id");
        $userResult = $this->lib_user->findUser(array('id' => $id));
        // 统计我的团队
        $userResult['data']['team_count'] = $this->getTeam($id);
        echo json_encode($userResult);
    }

    /**
     * Info: 统计团队数量
     * Date: 2022/11/10 10:29
     */
    private function getTeam($user_id)
    {
        $sql = <<< SQL
SELECT count(*) num FROM `base_user` WHERE `parent_id` = {$user_id}
SQL;
        $result = Db::query($sql);
        return $result[0]['num'];
    }

    /**************************************  用户分享二维码模块  ***********************************/
    /**
     * Info: 获取推广二维码
     * Date: 2022/11/28 10:00
     */
    function promotionPage()
    {
        $user_id = input('user_id');//用户id
        //查询用户推广二维码信息
        $targetPath = "upload/image/qrcode";//保存路径
        $condition = array('user_id' => $user_id);
        //判断是否已存在小程序码
        $result = $this->LibUserCode->findCode($condition);
        if ($result['errorCode'] == 0) {
            $wechatCode = Common::errorArray(0, '推广二维码已存在', $result['data']['code']);
        } else {
            //小程序码+用户头像
            $wxappCode = $this->getCode($user_id);
            $backgroundImg = "";//合成的背景图路径
            $wechatCode = $this->LibUserCode->getAppCode($condition, $targetPath, $wxappCode, $backgroundImg);
        }
        echo json_encode($wechatCode);
    }

    /**
     * Info: 获取小程序码
     * Date: 2022/11/28 10:00
     */
    function getCode($user_id)
    {
        $access_token = $this->getSetAccessToken();
        $path = "pages/index/index";//推广人的用户id
        $width = 55;//55,180,54
        $colorArr = array('r' => '55', 'g' => '180', 'b' => '54');
        $color = json_encode($colorArr);
        $auto = true;
        $post_data = '{"path":"' . $path . '","width":"' . $width . '"}';
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $access_token;
        $queryAction = 'POST';
        $result = Curl::callWebServer($url, $post_data, $queryAction, 0);
        $res = json_decode($result, true);
        //成功取得小程序二维码
        if (empty($res['errcode'])) {
            $time = time();
            $str = rand(0, 999);
            $name = $time . '_' . $str . '.png';
            $filepathDir = ROOT_PATH . 'public/upload/image/qrcode';
            $filepath = ROOT_PATH . 'public/upload/image/qrcode/' . $name;
            $fileUrl = 'upload/image/qrcode/' . $name;
            if (!file_exists($filepathDir)) {
                @mkdir($filepathDir, 0777, true);
            }
            file_put_contents($filepath, $result);
            $res = $fileUrl;
        }
        return $res;
    }

    /**
     * Info: 获取推广二维码
     * Date: 2022/11/28 10:00
     */
    private function getSetAccessToken()
    {
        $access_token = AccessToken::getAccessToken();
        return $access_token;
    }

    /**
     * Info: 获取用户微信头像
     * Date: 2022/11/28 10:00
     */
    private function getLogo($user_id)
    {
        //获取用户信息
        $userResult = $this->lib_user->findUser(array('id' => $user_id));
        //用户头像图片变圆形
        $avatar = file_get_contents($userResult['data']['head_img_url']);
        $logo = $this->yuanImg($avatar);//返回的是图片数据流
        return $logo;
    }

    /**
     * Info: 剪切图片为圆形
     * Date: 2022/11/28 10:00
     */
    private function yuanImg($picture)
    {
        $src_img = imagecreatefromstring($picture);
        $w = imagesx($src_img);
        $h = imagesy($src_img);
        $w = min($w, $h);
        $h = $w;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $w / 2; //圆半径
        $y_x = $r; //圆心X坐标
        $y_y = $r; //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        /**
         * 如果想要直接输出图片，应该先设header。header("Content-Type: image/png; charset=utf-8");
         * 并且去掉缓存区函数
         */
        //获取输出缓存，否则imagepng会把图片输出到浏览器
        ob_start();
        imagepng($img);
        imagedestroy($img);
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }

    /**
     * Info: 在二维码的中间区域镶嵌图片
     * Date: 2022/11/28 10:01
     */
    private function qrcodeWithLogo($QR, $logo)
    {
        $QR = imagecreatefromstring($QR);
        $logo = imagecreatefromstring($logo);
        $QR_width = imagesx($QR);//二维码图片宽度
        $QR_height = imagesy($QR);//二维码图片高度
        $logo_width = imagesx($logo);//logo图片宽度
        $logo_height = imagesy($logo);//logo图片高度
        $logo_qr_width = $QR_width / 2.2;//组合之后logo的宽度(占二维码的1/2.2)
        $scale = $logo_width / $logo_qr_width;//logo的宽度缩放比(本身宽度/组合后的宽度)
        $logo_qr_height = $logo_height / $scale;//组合之后logo的高度
        $from_width = ($QR_width - $logo_qr_width) / 2;//组合之后logo左上角所在坐标点
        /**
         * 重新组合图片并调整大小
         * imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
         */
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
        /**
         * 如果想要直接输出图片，应该先设header。header("Content-Type: image/png; charset=utf-8");
         * 并且去掉缓存区函数
         */
        //获取输出缓存，否则imagepng会把图片输出到浏览器
        ob_start();
        imagepng($QR);
        imagedestroy($QR);
        imagedestroy($logo);
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
}